<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/26
 * Time: 13:51
 */

namespace App\Api\Auth\Services;


use App\Api\Auth\Models\FunctionRoute;
use App\Api\Auth\Models\Functions;
use App\Api\Auth\Models\PermissionFunction;
use App\Api\Auth\Models\Permissions;
use App\Api\Auth\Models\PermissionUser;
use App\Api\Auth\Models\Routes;
use App\Api\Auth\Models\PermissionRoute;
use App\Api\Auth\Models\Users;
use App\Permission;
use Complex\Exception;
use DB;
use App\User;


class PermissionServices
{
    /*
     * api定义
     */
    public static function operationApi($params)
    {
        $id = data_get($params, 'id', '');
        try {
            if (!empty($id)) {
                $res = Routes::where('id', $id)->update($params);
                $arr = [
                    'tid'        => $id,
                    'table_name' => 'routes',
                    'log_info'   => '管理员修改api',
                    'remark'     => serialize($params)

                ];
            } else {
                $params['type']       = 2;
                $params['created_at'] = date('Y-m-d H:i:s');
                $res                  = Routes::insertGetId($params);
                $arr                  = [
                    'tid'        => $res,
                    'table_name' => 'routes',
                    'log_info'   => '管理员新增api',
                ];
            }
            $result = addAdminLogs($arr);
            return $result;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    /*
     * 删除api
     */
    public static function deleteApi($id)
    {
        DB::beginTransaction();
        try {
            Routes::where('id', $id)->delete();
            FunctionRoute::where('route_id', $id)->delete();
            $arr = [
                'tid'        => $id,
                'table_name' => 'routes',
                'log_info'   => '管理员删除api',
            ];
            $res = addAdminLogs($arr);
            if ($res == 'ok') {
                DB::commit();
            } else {
                DB::rollBack();
            }
            return $res;
        } catch (\Exception $e) {
            DB::rollBack();

            return $e->getMessage();
        }
    }

    /*
     * 操作岗位功能
     */
    public static function updatePermissionApi($params)
    {
        $permission_id = data_get($params, 'permission_id', '');
        $ids           = data_get($params, 'ids', '');
        if (empty($permission_id)) {
            return '参数不能为空';
        }
        $api_ids = explode(',', $ids);

        DB::beginTransaction();
        try {
            PermissionFunction::where('permission_id', $permission_id)->delete();
            foreach ($api_ids as $k => $v) {
                if (empty($v)) {
                    DB::rollBack();
                    return '相关功能提交异常，请重试';
                }
                PermissionFunction::create(['func_id' => $v, 'permission_id' => $permission_id]);
            }
            $arr = [
                'tid'        => $permission_id,
                'table_name' => 'permission_func',
                'log_info'   => '管理员操作岗位功能',
            ];
            $res = addAdminLogs($arr);
            if ($res == 'ok') {
                DB::commit();
            } else {
                DB::rollBack();
            }
            return $res;
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getMessage();
        }
    }

    /*
     * 删除岗位
     */
    public static function deletePermission($id)
    {
        $user   = authUser();
        $shopId = UserService::getShopId($user);
        DB::beginTransaction();
        try {
            $ok = Permissions::where([
                'id'      => $id,
                'shop_id' => $shopId//自己店铺限制
            ])->delete();//部门or岗位
            if ($ok) {
                Permissions::where('parent_id', $id)->delete();//若删除的是部门则也删除相关岗位
                PermissionFunction::where('permission_id', $id)->delete();
                PermissionUser::where('permission_id', $id)->delete();
            }
            DB::commit();
            return 'ok';
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getMessage();
        }
    }

    static function store($params)
    {

    }

    /***部门，岗位列表
     * @return array
     */
    static function rosList()
    {
        $user   = authUser();
        $shopId = UserService::getShopId($user);
        $ros_id = Permissions::where([
            'parent_id' => 0,
            'shop_id'   => $shopId,
            'level'     => 1,
        ])->value('id');
        if (!$ros_id) throw new \LogicException('系统id失效！请联系数据库管理员');
//        $depts = Permissions::select('id', 'name')->where('parent_id', $ros_id)->get();//部门
//        $depts = $depts->toArray() ? $depts : [];//dd($depts);//->toArray()
//        if (!empty($depts)) foreach ($depts as $key => $dept) {
//            $depts[$key]['data'] = Permissions::select('id', 'name', 'description')->where('parent_id', $dept->id)->get();
//        }
        $depts = Permissions::select('permissions.id as dept_id', 'permissions.name as dept', 'p.id', 'p.name', 'p.description')
            ->join('permissions as p', 'p.parent_id', '=', 'permissions.id')
            ->where('permissions.parent_id', $ros_id)->get();
        $datas = [];
        if (!empty($depts)) foreach ($depts as $dept) {
            $dept_id                   = data_get($dept, 'dept_id');
            $datas[$dept_id]['id']     = array_pull($dept, 'dept_id');
            $datas[$dept_id]['name']   = array_pull($dept, 'dept');
            $datas[$dept_id]['data'][] = $dept;
        }
        return array_values($datas);
    }

    /**员工列表
     * @param $params
     * @return mixed
     */
    public static function userList($params)
    {
        $user   = authUser();
        $shopId = UserService::getShopId($user);
        $page      = $params['page'];
        $pageSize  = $params['page_size'];
        $real_name = data_get($params, 'real_name', '');
        //$sql       = User::select('users.name as name', 'users.real_name', 'users.status', 'users.id');
        $sql = Users::select('business_users.login_name as name', 'business_users.real_name', 'business_users.status', 'business_users.id', 'p2.name as dept', 'p1.name as job')
            ->join('permission_user as pu', 'pu.user_id', '=', 'id')
            ->join('permissions as p1', 'pu.permission_id', '=', 'p1.id')//岗位
            ->join('permissions as p2', 'p2.id', '=', 'p1.parent_id')
            ->where('business_users.status', '>', -200);
        //->join('permissions as p3', 'p3.id', '=', 'p2.parent_id');//系统
        if ($real_name) $sql = $sql->where('business_users.real_name', 'like', '%' . $real_name . '%');
        $users = $sql->where('p2.shop_id', $shopId)->paginate($pageSize, ['*'], 'page', $page)->toArray();
        //$users = $sql->paginate($pageSize, ['*'], 'page', $page)->toArray();
        //$users = $users??[1];
        $data = data_get($users, 'data', []);
        if (!empty($data)) foreach ($data as $key => $user) {
            $data[$key]['status'] = data_get(Users::$status, $user['status']);
        }
        $users['data'] = $data;
        return $users;
    }

    /**新增员工
     * @param $params
     * @return mixed
     */
    static function userAdd($params)
    {
        $user   = authUser();
        $shopId = UserService::getShopId($user);
        $ok = ['name', 'real_name', 'password', 'permission_id'];
        foreach (array_keys($params) as $key) {
            if (!in_array($key, $ok)) throw new \LogicException('新增用户参数非法！');
        }
        $params2Create['login_name'] = $params['name'].'@'.data_get(Users::where('id', '=', $user->id)->first(), 'login_name', '');
        if (Users::where('login_name', $params2Create['login_name'])->first()) throw new \LogicException('用户名已存在！');
        $params2Create['password'] = bcrypt($params['password']);
        $permission_id      = array_pull($params, 'permission_id');//试试
//        $permission_id      = $params['permission_id'];
//        unset($params['permission_id']);
        $params2Create['api_token'] = str_random(50);
        $params2Create['real_name'] = $params['real_name'];
//        $params['created_at'] = date('Y-m-d H:i:s');
//        $params['updated_at'] = date('Y-m-d H:i:s');
        $params2Create['shop_id'] = $shopId;
//        $params['login_name'] = $params['name'];
        $user_id             = Users::insertGetId($params2Create);
        Users::find($user_id)
            ->update([
                'user_id' => $user_id
            ]);
        PermissionUser::updateOrCreate(['user_id' => $user_id, 'permission_id' => $permission_id]);
        return $user_id;
    }

    /**员工修改
     * @param $params
     * @return mixed
     */
    static function userUpdate($params)
    {
        $ok = ['name', 'real_name', 'password', 'permission_id'];
        foreach (array_keys($params) as $key) {
            if (!in_array($key, $ok)) throw new \LogicException('新增用户参数非法！');
        }
        if (User::where('name', $params['name'])->first()) throw new \LogicException('用户名已存在！');
        $params['password'] = bcrypt($params['password']);
        $permission_id      = $params['permission_id'];
        unset($params['permission_id']);
        $user_id = data_get(User::create($params), 'id');
        PermissionUser::updateOrCreate(['user_id' => $user_id, 'permission_id' => $permission_id]);
        return $user_id;
    }

    /**职位列表
     * @param $params
     * @return mixed
     */
    public static function permissionList($params)
    {
        $user   = authUser();
        $shopId = UserService::getShopId($user);
        $page      = $params['page'];
        $pageSize  = $params['page_size'];
        $level     = data_get($params, 'level', 3);
        $parent_id = data_get($params, 'parent_id', false);
        $sql       = Permissions::select('id', 'name', 'description')->where('level', $level)->where('shop_id',$shopId);
        if ($parent_id !== false) $sql = $sql->where('parent_id', $parent_id);
        $Permissions = $sql->paginate($pageSize, ['*'], 'page', $page)->toArray();
        return $Permissions;
    }

    /**  职位部门 添加
     * @param $params
     * @return mixed
     */
    static function permissionAdd($params)
    {
       $user   = authUser();
        $shopId = UserService::getShopId($user);
//        $params['parent_id'] = 6;
//        $params['level'] = 2;
        if ($params['level'] == 3 && !isset($params['parent_id'])) throw new \LogicException('请传递上级部门id');
        if ($params['level'] == 2) $params['parent_id'] = Permissions::where('shop_id', $shopId)
            ->where('level',1)->where('parent_id',0)->value('id');
        $params['shop_id'] = $shopId;
        $params['created_at'] = date('Y-m-d h:i:s');
        if (Permissions::where(['shop_id'=>$shopId,'parent_id'=>$params['parent_id'],'name'=>$params['name']])->first())
            throw new \LogicException('店铺下已存在该名称');//部门或岗位名
        $data                 = Permissions::insert($params);
        return $data;
    }

    /**职位部门 修改
     * @param $params
     * @return mixed
     */

    static function permissionUpdate($params)
    {
        $params['updated_at'] = date('Y-m-d h:i:s');
        if (!isset($params['id'])) throw new \LogicException('id不能为空');
        $data = Permissions::where('id', $params['id'])->update($params);
        return $data;
    }

    static function permissionFunction($permission_id, $func_ids)
    {
        try {
            DB::beginTransaction();
            $family = [];//用于缓存已添加的父类，爷爷，如孙子A被添加则加B时 同样的爷爷爸爸不会被纳入查询判断
            if (is_array($func_ids) && !empty($func_ids)) foreach ($func_ids as $func_id) {
                $family = array_merge($family, self::addParentFunc($permission_id, $func_id, $family));
                $family = array_unique($family);
            }
            PermissionFunction::where('permission_id', $permission_id)->whereNotIn('func_id', $family)->delete();
            DB::commit();
            return 1;
        } catch (\Exception $e) {
            DB::rollBack();
            info('岗位功能调整错误' . $e->getMessage());
            return 0;
        }
    }

    /**绑定自己以及自己父类的功能
     * @param $permission_id
     * @param $func_id
     * @param array $family
     * @return array
     */
    static function addParentFunc($permission_id, $func_id, $family = [])
    {
        $family[] = $func_id;
        PermissionFunction::FirstOrCreate(['permission_id' => $permission_id, 'func_id' => $func_id]);
        $parent_id = Functions::where('id', $func_id)->value('parent_id');
        if (!in_array($parent_id, $family) && ($id = Functions::where('id', $parent_id)->value('id'))) {
            $family = static::addParentFunc($permission_id, $id, $family);
        }
        return $family;
    }

    /**api路由列表
     * @param $params
     * @return mixed
     */

    public static function routesList($params)
    {
        $page     = $params['page'];
        $pageSize = $params['page_size'];
        $sql      = Routes::select('id', 'name', 'description', 'route', 'type', 'created_at', 'updated_at');
        //if (isset($params['type']) && $params['type']) $sql = $sql->where('type',  $params['type'] );
        if (isset($params['name']) && $params['name']) $sql = $sql->where('name', 'like', '%' . $params['name'] . '%');
        if (isset($params['id']) && $params['id']) $sql = $sql->where('id', $params['id']);
        $routes = $sql->paginate($pageSize, ['*'], 'page', $page)->toArray();
        return $routes;
    }

    static function routeDelete($id)
    {
        Routes::where('id', $id)->delete();//功能 1 2 3 级
        FunctionRoute::where('route_id', $id)->delete();
    }

    /**功能列表
     * @param $params
     * @return array
     */
    public static function funcsList($params)
    {
        $page     = $params['page'];
        $pageSize = $params['page_size'];
        $sql      = Functions::select('functions.id', 'functions.name', 'functions.code', 'functions.parent_id', 'functions.grand_parent_id',
            'functions.description', 'functions.url', 'functions.created_at', 'functions.updated_at', 'f1.name as f1name', 'f2.name as f2name')
            ->leftjoin('functions as f1', 'f1.id', '=', 'functions.parent_id')
            ->leftjoin('functions as f2', 'f2.id', '=', 'f1.parent_id');
        if (isset($params['name']) && $params['name']) $sql = $sql->where('functions.name', 'like', '%' . $params['name'] . '%');
        if (isset($params['permission_id']) && $params['permission_id']) {
            $funcs = PermissionFunction::select('permission_id', 'func_id')->where('permission_id', $params['permission_id'])->get();
            if (!$funcs) {
                return [];
            } else {
                $funcs_ids = [];
                foreach ($funcs->toArray() as $key => $value) {
                    $funcs_ids[] = $value['func_id'];
                }
                $sql = $sql->whereIn('id', $funcs_ids);
            }
        }
        if (isset($params['parent_id'])) $sql = $sql->where('functions.parent_id', $params['parent_id']);
        $params['new'] ? $sql->where('functions.created_at', '>=', '2019-08-01') : $sql->where('functions.created_at', '<', '2019-08-01');
        $routes = $sql->paginate($pageSize, ['*'], 'page', $page)->toArray();
        return $routes;
    }

    public static function funcLists($id, $new)
    {
        $funcs = $new ? Functions::where('parent_id', $id)->where('created_at', '>=', '2019-08-01')->get() : Functions::where('parent_id', $id)->where('created_at', '<', '2019-08-01')->get();
        if (!empty($funcs)) {
            foreach ($funcs as $key => $func) {
                $funcs[$key]['data'] = static::funcLists($func['id'], $new);
            }
        }
        return $funcs;
    }

    static function funcDelete($id = [])
    {
        $funcs = Functions::whereIn('parent_id', $id)->get();
        if (!empty($funcs)) {
            $ids = [];
            foreach ($funcs as $key => $func) {
                data_get($func, 'id') ? $ids[] = data_get($func, 'id') : '';
            }
            if (!empty($ids)) self::funcDelete($ids);
        }
        Functions::whereIn('id', $id)->delete();//功能 1 2 3 级
        PermissionFunction::where('func_id', $id)->delete();
        FunctionRoute::where('func_id', $id)->delete();
    }

    /**
     * @param $params
     * @return mixed
     * 功能添加
     */
    static function funcsAdd($params)
    {
//        $params['parent_id'] = 6;
//        $params['level'] = 2;
        $isExist = Functions::where('name', $params['name'])->first();
        if ($isExist) throw new \LogicException('功能名称已存在');
        try{
            DB::beginTransaction();
            $params['created_at'] = date('Y-m-d h:i:s');
            $func_id              = Functions::insertGetId($params);
            //添加功能默认会为所有管理员添加
            $permission_ids = Permission::where(['parent_id' => 0, 'level' => 1])->pluck('id');
            $datas          = [];
            foreach ($permission_ids as $key => $permission_id) {
                $datas[$key] = [
                    'permission_id' => $permission_id,
                    'func_id'       => $func_id,
                ];
            }
            DB::table('permission_func')->insert($datas);
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            info('添加功能报错:'.$e->getMessage());
            throw $e;
        }
        return 'success';
    }

    /**
     * @param $params
     * @return mixed
     * 功能更新
     */
    static function funcsUpdate($params)
    {
        if (!isset($params['id'])) throw new \LogicException('id不能为空');
        $id      = $params['id'];
        $isExist = Functions::where('name', $params['name'])->where('id', '!=', $id)->first();
        if ($isExist) throw new \LogicException('功能名称已存在');
        $params['updated_at'] = date('Y-m-d h:i:s');
        $data                 = Functions::where('id', $id)->update($params);
        return $data;
    }

    /***
     * @param int $func_id
     * @param array $api_ids
     * @return int
     * 功能对应api路由
     */
    static function funcApi($func_id = 0, $api_ids = [0])
    {
        try {
            FunctionRoute::where('func_id', $func_id)->whereNotIn('route_id', $api_ids)->delete();
            if (is_array($api_ids) && !empty($api_ids)) foreach ($api_ids as $api_id) {
                FunctionRoute::FirstOrCreate(['func_id' => $func_id, 'route_id' => $api_id]);
            }
            return 1;
        } catch (\Exception $e) {
            info('功能对应api路由调整错误' . $e->getMessage());
            return 0;
        }
    }

    /**
     * @param int $func_id
     * @return mixed
     * 获取功能对应的api路由
     */
    static function funcApiList($func_id = 0)
    {
        return FunctionRoute::join('routes as r', 'r.id', '=', 'route_id')->where('func_id', $func_id)->get();
    }

}